package com.xxx.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.reggie.common.BaseContext;
import com.xxx.reggie.common.R;
import com.xxx.reggie.entity.Orders;
import com.xxx.reggie.entity.User;
import com.xxx.reggie.service.OrdersService;
import com.xxx.reggie.service.UserService;
import com.xxx.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.beans.beancontext.BeanContext;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private OrdersService ordersService;

    /**
     * 发送手机验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        //生成随机验证码
        if (StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码为:{}",code);
            //调用阿里云提供的短信服务API完成发送短信

            //需要将生成的验证码保存到Session中进行比对验证码
            session.setAttribute(phone,code);
            return R.success("短信发送成功!!");
        }

        return R.error("短信发送失败");
    }

    /**
     * 登录检测
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //获取session中的验证码
        Object attribute = session.getAttribute(phone);
        //比较
        if (attribute != null && attribute.equals(code)){
            //判断手机号是否是新用户,如果不是就保存到user表中
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(User::getPhone,phone);
            User list = userService.getOne(queryWrapper);
            if (list == null){
                //保存
                list = new User();
                list.setPhone(phone);
                list.setStatus(1);
                userService.save(list);
            }
            session.setAttribute("user",list.getId());
            //登陆成功
            return R.success(list);
        }

        return R.error("验证码错误,登录失败");
    }

}
